<script setup>
import { ref, onMounted } from "vue";
import {
  queryPageApi,
  queryDeptListApi,
  queryRoleListApi,
  addUserApi,
  queryUserInfoApi,
  updateUserApi,
  deleteUserApi,
} from "@/api/user";
import { ElMessage, ElMessageBox } from "element-plus";

const token = ref("");

// 查询参数
const queryParams = ref({
  name: "",
  phone: "",
  deptId: "",
  status: "",
  page: 1,
  pageSize: 10,
});

// 表格数据
const userList = ref([]);
const total = ref(0);
const deptList = ref([]);
const roleList = ref([]);
const selectedUsers = ref([]);

// 表单相关
const userFormRef = ref();
const userForm = ref({
  username: "",
  name: "",
  phone: "",
  email: "",
  gender: "",
  status: "",
  deptId: "",
  roleId: "", // 确保默认值存在
  image: "",
  remark: "",
});

// 对话框
const dialog = ref({
  title: "",
  visible: false,
});

// 表单验证规则
const rules = ref({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
    { min: 5, max: 50, message: "长度在 5 到 50 个字符", trigger: "blur" },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
});

// 文件上传相关
const uploadAction = "/api/upload"; // 根据实际接口调整

onMounted(() => {
  loadDeptList();
  loadRoleList();
  search();

  token.value = localStorage.getItem("token");
});

// 加载部门列表
const loadDeptList = async () => {
  const result = await queryDeptListApi();
  if (result.code === 1) {
    deptList.value = result.data;
  }
};

// 加载角色列表
const loadRoleList = async () => {
  const result = await queryRoleListApi();
  if (result.code === 1) {
    roleList.value = result.data;
  }
};

// 查询按钮
const search = async () => {
  const result = await queryPageApi(queryParams.value);
  if (result.code === 1) {
    userList.value = result.data.rows;
    total.value = result.data.total;
  } else {
    ElMessage.error(result.msg || "查询失败");
  }
};

// 重置查询
const clear = () => {
  queryParams.value = {
    name: "",
    phone: "",
    deptId: "",
    status: "",
    page: 1,
    pageSize: 10,
  };
  search();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  search();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.page = val;
  search();
};

// 选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection;
};

// 添加用户按钮
const handleAdd = () => {
  dialog.value.title = "新增用户";
  dialog.value.visible = true;
  userForm.value = {
    username: "",
    name: "",
    phone: "",
    email: "",
    gender: "",
    status: "",
    deptId: "",
    roleId: "",
    image: "",
    remark: "",
  };
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
};

// 修改用户按钮
const handleEdit = async (id) => {
  const result = await queryUserInfoApi(id);
  if (result.code === 1) {
    userForm.value = result.data;
    // 确保 roleList 中存在对应的 roleName
    const role = roleList.value.find(r => r.id === userForm.value.roleId);
    if (role) {
      userForm.value.roleName = role.name;
    }
    dialog.value.title = "修改用户";
    dialog.value.visible = true;
    if (userFormRef.value) {
      userFormRef.value.resetFields();
    }
  } else {
    ElMessage.error(result.msg);
  }
};

// 删除用户按钮
const handleDelete = async (id) => {
  ElMessageBox.confirm("您确认要删除该用户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const result = await deleteUserApi(id);
    if (result.code === 1) {
      ElMessage.success("删除成功");
      search();
    } else {
      ElMessage.error(result.msg || "删除失败");
    }
  });
};

// 批量删除按钮
const handleBatchDelete = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning("请选择要删除的用户");
    return;
  }

  const ids = selectedUsers.value.map((user) => user.id).join(",");
  ElMessageBox.confirm(
    `确认要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    const result = await deleteUserApi(ids);
    if (result.code === 1) {
      ElMessage.success("批量删除成功");
      search();
    } else {
      ElMessage.error(result.msg || "批量删除失败");
    }
  });
};

// 保存按钮
const save = async () => {
  userFormRef.value.validate(async (valid) => {
    if (!valid) return;
    let result;
    if (userForm.value.id) {
      // 修改用户
      result = await updateUserApi(userForm.value);
    } else {
      // 添加用户
      result = await addUserApi(userForm.value);
    }

    if (result.code === 1) {
      dialog.value.visible = false;
      ElMessage.success(userForm.value.id ? "修改成功" : "添加成功");
      search();
    } else {
      ElMessage.error(result.msg || "操作失败");
    }
  });
};

// 头像上传成功
const handleAvatarSuccess = (response, file) => {
  if (response.code === 1) {
    userForm.value.image = response.data;
    ElMessage.success("头像上传成功");
  } else {
    ElMessage.error(response.msg || "头像上传失败");
  }
};

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/jpg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("头像只能是 JPG/PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!");
    return false;
  }
  return true;
};
</script>

<template>
  <div class="user">
    <el-card class="user-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>添加用户
            </el-button>
            <el-button type="danger" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-card class="search-card" shadow="never">
        <el-form
          :inline="true"
          :model="queryParams"
          ref="queryForm"
          class="search-form"
        >
          <el-form-item label="姓名">
            <el-input v-model="queryParams.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="queryParams.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="部门">
            <el-select
              v-model="queryParams.deptId"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="dept in deptList"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择"
              clearable
            >
              <el-option label="正常" :value="1" />
              <el-option label="停用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item class="search-buttons">
            <el-button type="primary" @click="search">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button type="info" @click="clear">
              <el-icon><Refresh /></el-icon>清空
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 表格区域 -->
      <el-table
        :data="userList"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="姓名" width="150" align="center" />
        <el-table-column
          prop="username"
          label="用户名"
          width="150"
          align="center"
        />
        <el-table-column label="头像" width="120" align="center">
          <template #default="scope">
            <el-avatar :size="35" :src="scope.row.image" :icon="UserFilled" />
          </template>
        </el-table-column>
        <el-table-column
          prop="deptName"
          label="部门"
          width="150"
          align="center"
        />
        <el-table-column
          prop="roleName"
          label="角色"
          width="150"
          align="center"
        />
        <el-table-column
          prop="phone"
          label="手机号"
          width="120"
          align="center"
        />
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? "正常" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="最后操作时间"
          width="180"
          align="center"
        />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row.id)">
              <el-icon><Edit /></el-icon>修改
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row.id)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 40, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/修改用户对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="800px"
      class="user-dialog"
    >
      <el-form
        :model="userForm"
        ref="userFormRef"
        :rules="rules"
        label-width="80px"
        class="user-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="userForm.username"
                placeholder="请输入用户名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="userForm.gender"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="userForm.status"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="正常" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="userForm.deptId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="dept in deptList"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select
                v-model="userForm.roleId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="{'token': token }"
            name="image"
          >
            <img v-if="userForm.image" :src="userForm.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            图片上传,支持扩展名: .png/.jpg/.jpeg 大小限制: 2M
          </div>
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input
            v-model="userForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入用户的备注信息,最多200字"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">
          <el-icon><Close /></el-icon>取 消
        </el-button>
        <el-button type="primary" @click="save">
          <el-icon><Check /></el-icon>确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100%;
}

.user-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 6px;
  background-color: #fafafa;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form :deep(.el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
  min-width: 250px;
}

.search-buttons {
  margin-left: auto !important;
  min-width: auto !important;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

/* 用户对话框样式 */
:deep(.user-dialog .el-dialog__body) {
  padding-top: 30px;
}

.user-form {
  width: 90%;
  margin: 0 auto;
}

/* 头像上传样式 */
.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
  line-height: 80px;
  border: #d8d4d4 solid 1px;
  border-radius: 10%;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
  border: #d8d4d4 solid 1px;
  border-radius: 10%;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .header-actions {
    width: 100%;
    justify-content: space-between;
  }

  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-form :deep(.el-form-item) {
    width: 100%;
    min-width: auto;
  }

  .search-buttons {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .search-buttons .el-button {
    flex: 1;
    margin-right: 10px;
  }

  .search-buttons .el-button:last-child {
    margin-right: 0;
  }
}
</style>
